#include <REGX52.H>
#include "uart.c"
#include "gpio_pin.c"

/**
 * 记录的数据长度增加
 * 可以记录熄灭的状态
 */

#define RECORDS_MAX 100

unsigned char idata key_records[RECORDS_MAX];
// 数组可以记录不满，使用index保存记录总量的最后一位的位置
unsigned char records_index = 0;

GPIO_PIN code keys[] = {
    PIN(1, 0),
    PIN(1, 1),
    PIN(1, 2),
    PIN(1, 3),
    PIN(1, 4),
    PIN(1, 5),
    PIN(1, 6),
    PIN(1, 7),
    PIN(3, 6),
    PIN(3, 7),
};

#define KEY_COUNT (sizeof(keys) / sizeof(keys[0]))

GPIO_PIN code leds[] = {
    PIN(2, 0),
    PIN(2, 1),
    PIN(2, 2),
    PIN(2, 3),
    PIN(2, 4),
    PIN(2, 5),
    PIN(2, 6),
    PIN(2, 7)};

#define KEYS P1
#define LEDS P2
sbit KEY_RECORD = P3 ^ 6;
sbit KEY_PLAY = P3 ^ 7;
#define PRESSED_RECORD 8
#define PRESSED_PLAY 9

#define STATE_RECORD 1
#define STATE_PLAY 2

unsigned char state = STATE_RECORD;

void delay_ms(unsigned int ms)
{
    unsigned int i, j;
    for (i = 0; i < ms; i++)
    {
        for (j = 0; j < 123; j++)
            ;
    }
}


void play()
{
    unsigned char i;
    LEDS = 0xFF;
    while (1)
    {
        for (i = 0; i < records_index; i++)
        {
            gpio_revert(leds[key_records[i]]);
            delay_ms(500);
            if (KEY_RECORD == 0)
            {
                while (KEY_RECORD == 0)
                {
                }
                state = STATE_RECORD;
                return;
            }
        }

        if (KEY_RECORD == 0)
        {
            while (KEY_RECORD == 0)
            {
            }
            state = STATE_RECORD;
            return;
        }
    }
}

void record_keys()
{
    unsigned char key;
    LEDS = 0xFF;
    records_index = 0;
    // 播放按键被按下，结束

    while (1)
    {
        key = key_scan(keys, KEY_COUNT);
        if (key == PRESSED_PLAY)
        {
            state = STATE_PLAY;
            return;
        }

        if ((key != KEY_PRESSED_NONE) && (key != PRESSED_RECORD))
        {
            key_records[records_index] = key;
            records_index++;
            gpio_revert(leds[key]);
        }
    }
}

void main()
{
    unsigned char key;
    uart_init();
    while (1)
    {
        switch (state)
        {
        case STATE_PLAY:
            play();
            break;
        case STATE_RECORD:
            record_keys();
            break;
        default:
            break;
        }
    }
}